﻿using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using UnityEngine;

namespace FrameWorkSong
{
    /// <summary>
    /// 文件日志类
    /// </summary>
    // [特性(布局种类.有序,字符集=字符集.自动)]
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public class ChinarFileDlog
    {
        public int structSize = 0;
        public IntPtr dlgOwner = IntPtr.Zero;
        public IntPtr instance = IntPtr.Zero;
        public String filter = null;
        public String customFilter = null;
        public int maxCustFilter = 0;
        public int filterIndex = 0;
        public String file = null;
        public int maxFile = 0;
        public String fileTitle = null;
        public int maxFileTitle = 0;
        public String initialDir = null;
        public String title = null;
        public int flags = 0;
        public short fileOffset = 0;
        public short fileExtension = 0;
        public String defExt = null;
        public IntPtr custData = IntPtr.Zero;
        public IntPtr hook = IntPtr.Zero;
        public String templateName = null;
        public IntPtr reservedPtr = IntPtr.Zero;
        public int reservedInt = 0;
        public int flagsEx = 0;
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public class OpenFileDlg : ChinarFileDlog
    {
    }

    public class OpenFileDialog
    {
        [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
        public static extern bool GetOpenFileName([In, Out] OpenFileDlg ofd);
    }

    public class SaveFileDialog
    {
        [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
        public static extern bool GetSaveFileName([In, Out] SaveFileDlg ofd);
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public class SaveFileDlg : ChinarFileDlog
    {
    }

    public class FileMgr:Singleton<FileMgr>
    {
        /// <summary>
        /// 安装路径
        /// </summary>
        private string dataPath;
        /// <summary>
        /// 安装路径下StreamingAssets
        /// </summary>
        private string assetsPath;
        /// <summary>
        /// 长期持有路径
        /// </summary>
        private string persistentPath;
        /// <summary>
        /// 临时缓存路径
        /// </summary>
        private string cachePath;

        public string DataPath { get { return Application.dataPath + " / "; } }
        public string AssetsPath { get { return Application.streamingAssetsPath + "/"; } }
        public string PersistentPath { get { return Application.persistentDataPath + "/"; } }
        public string CachePath { get { return Application.temporaryCachePath + "/"; } }
        /// <summary>
        /// 文本保存到文档
        /// </summary>
        /// <param name="path">本地保存路径</param>
        /// <param name="fileName">文件名称带后缀</param>
        /// <param name="jsonData">文字数据</param>
        public void StrFileWrite(string path, string fileName, string jsonData)
        {
           
                string filePath = path + fileName;
                StrFileWrite(filePath, jsonData);
        }
        public void StrFileWrite(string filePath, string jsonData)
        {
            try
            {
                if (File.Exists(filePath))
                {
                    //如果文件存在删除该文件
                    File.Delete(filePath);
                }
                FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
                sw.WriteLine(jsonData);
                sw.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                Debug.LogError(ex);
            }
        }
        /// <summary>
        /// 判断是否有该文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public bool IsHaveFile(string path, string fileName)
        {
            string filePath = path + fileName;
            FileInfo fileInfo = new FileInfo(filePath);
            if (!fileInfo.Exists)//如果本地没有文件
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        /// <summary>
        /// 读取文档文字
        /// </summary>
        /// <param name="path">本地保存路径</param>
        /// <param name="fileName">文件名称带后缀</param>
        /// <returns>文件里的文字</returns>
        public string StrFileRead(string path, string fileName)
        {
            string filePath = path + fileName;
            string data = string.Empty;
            if (IsHaveFile(path, fileName))//如果本地没有文件
            {
                try
                {
                    FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                    StreamReader sr = new StreamReader(fs, Encoding.UTF8);
                    data = sr.ReadToEnd();
                    sr.Close();
                    fs.Close();
                    return data;
                }
                catch 
                {
                    return "";
                }
            }
            else
            {
                return "";
            }
        }
        public string StrFileRead(string filePath)
        {
            string data = string.Empty;
            try
            {
                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(fs, Encoding.UTF8);
                data = sr.ReadToEnd();
                sr.Close();
                fs.Close();
                return data;
            }
            catch
            {
                return "";
            }
        }
        /// <summary>
        /// 保存文本资源到本地
        /// </summary>
        /// <param name="path">本地保存路径</param>
        /// <param name="fileName">文件名称带后缀</param>
        /// <param name="bytes">byte数据</param>
        /// <param name="byteLength"></param>
        public void SaveAssetFile(string path, string fileName, byte[] bytes)
        {
            string filePath = path + fileName;
            SaveAssetFile(filePath, bytes);
        }
        public void SaveAssetFile(string filePath, byte[] bytes)
        {
       
            Stream sw = null;
            FileInfo fileInfo = new FileInfo(filePath);
            int byteLength = bytes.Length;
            if (fileInfo.Exists)
            {
                //如果文件存在删除该文件
                File.Delete(filePath);
                Debug.Log("删除文件:" + filePath);
            }
            sw = fileInfo.Create();
            sw.Write(bytes, 0, byteLength);//写入
            sw.Flush();//关闭流
            sw.Close();//销毁流
            sw.Dispose();
            Debug.Log(filePath + "成功保存到本地~");
        }

        /// <summary>
        /// 得到保存地址
        /// </summary>
        /// <param name="savetype">保存类型如（txt）</param>
        /// <param name="saveFile">保存方法</param>
        public void GetPath(string savetype,Action<string> saveFile)
        {
            SaveFileDlg pth = new SaveFileDlg();
            pth.structSize = Marshal.SizeOf(pth);
            pth.filter = "."+ savetype;
            pth.file = new string(new char[256]);

            //   pth.file = siteName.text + DateTime.Now.Date;
            pth.maxFile = pth.file.Length;
            pth.fileTitle = new string(new char[64]);
            //pth.fileTitle = siteName.text + DateTime.Now.Date;
            pth.maxFileTitle = pth.fileTitle.Length;
            pth.initialDir = Application.dataPath; //默认路径
            pth.title = "保存";
            pth.defExt = savetype;
            pth.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;
            if (SaveFileDialog.GetSaveFileName(pth))
            {
                //成功
                string filepath = pth.file; //选择的文件路径;  
                saveFile(filepath);
              
            }
            else
            {
               //失败
            }
        }
        /// <summary>
        /// 得到打开地址
        /// </summary>
        /// <param name="savetype">保存打开如（"txt文件\0*.txt\0json文件\0*.json\0所有文件\0*.*"）</param>
        /// <param name="saveFile">保存打开</param>
        public void OpenPath(string opentype, Action<string> getPath)
        {
            OpenFileDlg pth = new OpenFileDlg();
            pth.structSize = Marshal.SizeOf(pth);
            // pth.filter = "txt文件\0*.txt\0json文件\0*.json\0所有文件\0*.*";
            pth.filter = opentype;
            pth.file = new string(new char[256]);

            //   pth.file = siteName.text + DateTime.Now.Date;
            pth.maxFile = pth.file.Length;
            pth.fileTitle = new string(new char[64]);
            //pth.fileTitle = siteName.text + DateTime.Now.Date;
            pth.maxFileTitle = pth.fileTitle.Length;
            pth.initialDir = Application.dataPath; //默认路径
            pth.title = "打开";
            pth.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000008;
            if (OpenFileDialog.GetOpenFileName(pth))
            {
                getPath(pth.file);
                //SelectFilePath = pth.file;
                //FileName = pth.file;
            }
        }
        /// <summary>
        /// 打开文件/应用程序
        /// </summary>
        /// <param name="filePath"></param>
        public void OpenFile(string filePath)
        {
            Application.OpenURL(filePath);
        }
        public override void OnBeforeDestroy()
        {
           
        }
    }
}
